package com.zhongjianjian.Aopjiaoyanjiekoumidengxing.qiemian;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Pointcut;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * 作者: lgt
 * 日期: 2020/2/21 00:34
 * 描述:
 */
@Component
@Aspect
public class MyAopAspect {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Pointcut("execution(public * com.zhongjianjian.Aopjiaoyanjiekoumidengxing.*.*(..))")
    public void qierudian(){}

    @Around("qierudian() && @annotation(com.zhongjianjian.jiaoan.jiaoyanjiekoumidengxing.zhujie.ForCheck)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        ServletRequestAttributes requestAttributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String key=request.getParameter("token");


        //方式一
        /*boolean checkok = checkok(key);
        if(checkok){
            return joinPoint.proceed();
        }else{
            return "不可重复调用接口";
        }*/


        //方式二
        String check="if redis.call('get',KEYS[1]) then return redis.call('del',KEYS[1]) else return 0 end";
        DefaultRedisScript<Long> defaultRedisScript=new DefaultRedisScript();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setScriptText(check);//设置Lua脚本


        Object execute = redisTemplate.execute(defaultRedisScript, Collections.singletonList(key));
        System.out.println("===redis==="+execute);

        if(execute.toString().equals("1")){
            return joinPoint.proceed();
        }else{
            return "不可重复调用接口";
        }

    }


    public boolean checkok(String toekn){

        String s = redisTemplate.opsForValue().get(toekn);

        if(s!=null){
            System.out.println("----------");
            Boolean delete = redisTemplate.delete(toekn);
            return delete;
        }else{
            return false;
        }

    }    

}
